package com.winxuan.channel.support.view.excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;


/**
 * Excel 视图展示
 * 
 * @author HideHai
 * @version 1.0,2011-6-19
 */
public class ExcelView extends AbstractExcelView{


	private static final String DEFAULT_CONTENT_TYPE = "application/vnd.ms-excel";

	private static final Log LOG = LogFactory.getLog(ExcelView.class);
	private String excelTemplatePath;
	private boolean error;

	public ExcelView(){
		setContentType(DEFAULT_CONTENT_TYPE);
	}

	@Override
	protected void buildExcelDocument(Map<String, Object> map,
			HSSFWorkbook workbook, HttpServletRequest rquest, HttpServletResponse response)
	throws Exception {
		InputStream in = null;
		try {
			in = getTemplateSource(excelTemplatePath);
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ System.currentTimeMillis()+".xls\"");
			XLSTransformer transformer = new XLSTransformer();
			workbook = transformer.transformXLS(in, map);
			OutputStream out = response.getOutputStream();
			workbook.write(out);
			out.flush();
		} catch (FileNotFoundException e) {
			LOG.warn("The excel template file [" + excelTemplatePath+ "] not found");
			response.setStatus(404);
			return;
		}finally{
			if (in != null)
				in.close();
		}
	}



	private InputStream getTemplateSource(String url) throws Exception {
		return new FileInputStream(new java.io.File(url));
	}

	public String getExcelTemplatePath() {
		return excelTemplatePath;
	}

	public void setExcelTemplatePath(String excelTemplatePath) {
		this.excelTemplatePath = excelTemplatePath;
	}

	public boolean isError() {
		return error;
	}

	public void setError(boolean error) {
		this.error = error;
	}

}
